package com.ruoyi.app.api;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.BusinessConst;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.CustomId;
import com.ruoyi.system.domain.wx.WxUser;
import com.ruoyi.system.domain.wx.pay.WxPayShareMapper;
import com.ruoyi.system.service.wx.IWxUserService;
import com.ruoyi.system.service.wx.pay.IWxPayShareMapperService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 微信支出api
 *
 * @author mic
 * @date 2023年8月14日16:15:17
 */
@RestController
@RequestMapping("/wx/share")
public class WxpayShareMapperAPI {

    @Autowired
    private IWxPayShareMapperService shareMapperService;
    @Autowired
    private IWxUserService userService;

    /**
     * 获取当前用户的分享映射
     *
     * @param request
     * @param flag    0:记账时 1:分享配置 2:首页 分享给我的
     * @return
     */
    @GetMapping("/getBelongBy")
    public AjaxResult getBelongBy(HttpServletRequest request, String flag) {
        String userId = (String) request.getAttribute("userId");
        WxPayShareMapper shareMapper = new WxPayShareMapper();
        shareMapper.setStatus(BusinessConst.YesOrNo.NO);

        // 互看 我创建
        shareMapper.setBelongBy(userId);
        shareMapper.setFlag(BusinessConst.shareFlag.MUTUAL);
        List<WxPayShareMapper> whList = shareMapperService.selectWxPayShareMapperList(shareMapper);
        // 互看 ta创建
        shareMapper.setBelongBy(null);
        shareMapper.setViewBy(userId);
        List<WxPayShareMapper> thList = shareMapperService.selectWxPayShareMapperList(shareMapper);
        // 看后 ta创建
        shareMapper.setViewBy(userId);
        shareMapper.setFlag(BusinessConst.shareFlag.REAR);
        List<WxPayShareMapper> tfList = shareMapperService.selectWxPayShareMapperList(shareMapper);
        // 看前 我创建
        shareMapper.setViewBy(null);
        shareMapper.setBelongBy(userId);
        shareMapper.setFlag(BusinessConst.shareFlag.FRONT);
        List<WxPayShareMapper> tqList = shareMapperService.selectWxPayShareMapperList(shareMapper);

        if (BusinessConst.YesOrNo.NO.equals(flag)) {
            // 建账单时
            // 互看 我创建
            List<JSONObject> jsonsO = shareMapperService.handleViewBy(whList, BusinessConst.YesOrNo.NO);
            // 互看 ta创建
            List<JSONObject> jsonsW = shareMapperService.handleViewBy(thList, BusinessConst.YesOrNo.YES);
            // 看后 ta创建
            List<JSONObject> jsonsT = shareMapperService.handleViewBy(tfList, BusinessConst.YesOrNo.YES);
            // 看前 我创建
            List<JSONObject> jsonsF = shareMapperService.handleViewBy(tqList, BusinessConst.YesOrNo.NO);
            // 合并
            jsonsO.addAll(jsonsW);
            jsonsO.addAll(jsonsT);
            jsonsO.addAll(jsonsF);
            // 过滤重复数据
            List<JSONObject> jsons = jsonsO.stream().distinct().collect(Collectors.toList());

            return AjaxResult.success(jsons);
        } else if (BusinessConst.YesOrNo.YES.equals(flag)) {
            // 分享配置 列表
            // 互看
            JSONObject json = new JSONObject();
            whList.addAll(thList);
            json.put("xianghu", whList);
            // 看我
            tfList.addAll(tqList);
            json.put("kanwo", tfList);
            // 看他
            // 看前 ta创建
            shareMapper.setViewBy(userId);
            shareMapper.setBelongBy(null);
            shareMapper.setFlag(BusinessConst.shareFlag.FRONT);
            List<WxPayShareMapper> uList = shareMapperService.selectWxPayShareMapperList(shareMapper);
            // 看后 我创建
            shareMapper.setViewBy(null);
            shareMapper.setBelongBy(userId);
            shareMapper.setFlag(BusinessConst.shareFlag.REAR);
            List<WxPayShareMapper> qList = shareMapperService.selectWxPayShareMapperList(shareMapper);
            uList.addAll(qList);
            json.put("kanta", uList);
            return AjaxResult.success(json);
        } else if ("2".equals(flag)) {
            // 首页 分享给我的人
            WxPayShareMapper mapper = new WxPayShareMapper();
            mapper.setStatus(BusinessConst.shareStatus.PASS);
            mapper.setBelongBy(userId);
            List<WxPayShareMapper> mappers = shareMapperService.selectWxPayShareMapperList(mapper);
            List<JSONObject> list = new ArrayList<>();
            for (int i = 0; i < mappers.size(); i++) {
                // 处理昵称 或 viewId
                JSONObject json = new JSONObject();
                String viewName = mappers.get(i).getViewName();
                if (StringUtils.isBlank(viewName)) {
                    WxUser wxUser = userService.selectWxUserByUserId(mappers.get(i).getViewBy());
                    viewName = "用户ID:" + wxUser.getViewId();
                }
                json.put("nickName", viewName);
                json.put("userId", mappers.get(i).getViewBy());
                list.add(json);
            }
            return AjaxResult.success(list);
        }

        return AjaxResult.error("请求被拒绝!");

    }

    /**
     * 新增 - 更新用户id和分享码 flag
     */
    @RequestMapping("/insertShareMapper")
    public AjaxResult insertShareMapper(HttpServletRequest request, String viewId, String shareId, String nickName, String remark) {
        // 当前用户
        String userId = (String) request.getAttribute("userId");
        // 查找用户
        Map<String, String> map = new HashMap<>();
        map.put("viewId", viewId);
        map.put("shareId", shareId);
        WxUser user = userService.selectUserByShare(map);
        if (user == null) {
            return AjaxResult.error("未找到对应用户!");
        } else {
            // 找到已存在的映射关系是否已存在
            WxPayShareMapper shareMapper = new WxPayShareMapper();
            shareMapper.setBelongBy(userId);
            shareMapper.setViewBy(user.getUserId());
            List<WxPayShareMapper> wxPayShareMappers = shareMapperService.selectWxPayShareMapperList(shareMapper);
            if (wxPayShareMappers != null && wxPayShareMappers.size() > 0) {
                if (wxPayShareMappers.get(0).getStatus().equals("0")) {
                    // 已存在有效数据
                    return AjaxResult.error("该用户与你的分享配置已存在!");
                } else {
                    wxPayShareMappers.get(0).setStatus("0");
                    shareMapperService.updateWxPayShareMapper(wxPayShareMappers.get(0));
                    return AjaxResult.success("添加成功，待确认！");
                }
            }
        }
        // 新建记录
        WxPayShareMapper shareMapper = new WxPayShareMapper();
        shareMapper.setBelongId("s" + CustomId.timestamp());
        shareMapper.setBelongBy(userId);
        shareMapper.setRemarks(remark);
        shareMapper.setViewBy(user.getUserId());
        shareMapper.setCreateTime(new Date());
        shareMapper.setStatus(BusinessConst.shareStatus.ING);   // 待确认
        shareMapper.setFlag(BusinessConst.shareFlag.REAR);  // 2 看后
        shareMapper.setUpdateTime(new Date());
        shareMapper.setUpdateBy(userId);
        shareMapper.setViewName(nickName);

        shareMapperService.insertWxPayShareMapper(shareMapper);

        return AjaxResult.success("添加成功，待确认！");
    }

    /**
     * 处理待确认
     */
    @RequestMapping("/updateShareMapper")
    public AjaxResult updateShareMapper(HttpServletRequest request, WxPayShareMapper shareMapper) {
        // 当前用户
        String userId = (String) request.getAttribute("userId");

        WxPayShareMapper share = shareMapperService.selectWxPayShareMapperByBelongId(shareMapper.getBelongId());
        if (share != null && userId.equals(share.getViewBy())) {
            BeanUtils.copyProperties(shareMapper, share);
            share.setUpdateTime(new Date());
            share.setUpdateBy(userId);
            shareMapperService.updateWxPayShareMapper(share);
            return AjaxResult.success("确认成功!");
        }
        return AjaxResult.error("数据异常!");
    }

    /**
     * 分享通知列表
     */
    @RequestMapping("/todoInform")
    public AjaxResult todoInform(HttpServletRequest request) {
        // 当前用户
        String userId = (String) request.getAttribute("userId");

        // status =2
        WxPayShareMapper shareMapper = new WxPayShareMapper();
        shareMapper.setStatus(BusinessConst.shareStatus.ING);
        shareMapper.setViewBy(userId);
        List<WxPayShareMapper> wxPayShareMappers = shareMapperService.selectWxPayShareMapperList(shareMapper);

        // 数据结构 - 前端结构
        List<JSONObject> list = new ArrayList<>();
        // 关系描述
        for (int i = 0; i < wxPayShareMappers.size(); i++) {
            // 获取用户view_Id
            WxUser wxUser = userService.selectWxUserByUserId(wxPayShareMappers.get(i).getBelongBy());
            JSONObject json = new JSONObject();
            json.put("userId", "用户ID:" + wxUser.getViewId());
            json.put("conten", DictUtils.getDictLabel("share_content", wxPayShareMappers.get(i).getFlag()));
            json.put("belongId", wxPayShareMappers.get(i).getBelongId());
            json.put("remarks", wxPayShareMappers.get(i).getRemarks());
            json.put("nickName", wxPayShareMappers.get(i).getBelongName());
            list.add(json);
        }
        return AjaxResult.success(list);
    }

    /**
     * 分享 消息
     */
    @RequestMapping("/selectByMe")
    public AjaxResult selectByMe(HttpServletRequest request) {
        String userId = (String) request.getAttribute("userId");
        WxPayShareMapper shareMapper = new WxPayShareMapper();
        // 创建给我的 且状态为2(待确认)
        shareMapper.setViewBy(userId);
        shareMapper.setStatus(BusinessConst.shareStatus.ING);
        List<WxPayShareMapper> list = shareMapperService.selectWxPayShareMapperList(shareMapper);

        List<JSONObject> jsonObjectList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            JSONObject json = new JSONObject();
            WxUser wxUser = userService.selectWxUserByUserId(list.get(i).getBelongBy());
            if (wxUser != null) {
                json.put("id", "用户ID:" + wxUser.getViewId());
                json.put("conten", DictUtils.getDictLabel("share_content", BusinessConst.shareFlag.REAR));
                json.put("remarks", list.get(i).getRemarks());
                json.put("status", DictUtils.getDictLabel("share_status", list.get(i).getStatus()));
                shareMapper.setBelongBy(userId);
                shareMapper.setViewBy(list.get(i).getBelongBy());
                shareMapper.setStatus(null);
                List<WxPayShareMapper> mappers = shareMapperService.selectWxPayShareMapperList(shareMapper);
                if (mappers != null && mappers.size() > 0) {
                    json.put("nickName", mappers.get(0).getViewName());
                }
            }
            jsonObjectList.add(json);
        }
        return AjaxResult.success(jsonObjectList);
    }
}
